import tkinter as tk
from PIL import ImageTk
from tkinter import messagebox
import socket
import time
import _thread
import threading

window = tk.Tk()
# window.attributes('-topmost', 'true')
# window.after_idle(window.attributes,'-topmost',False)
window.title('Python Socket & C Socket')       # 设置窗口的标题
window.geometry('500x400')     # 设置窗口的大小

# 输入框的提示语
tk.Label(window, text="  IP:").place(x=15, y=50, anchor='nw')
tk.Label(window, text="PORT:").place(x=15, y=80, anchor='nw')

# 两个输入框
ip_var = tk.StringVar()
port_var = tk.StringVar()
en1 = tk.Entry(window, textvariable=ip_var)
en2 = tk.Entry(window, textvariable=port_var)

en1.place(x=70, y=50, anchor='nw')
# en1.insert(0, '10.201.0.26')
en1.insert(0, '192.168.43.240')

en2.place(x=70, y=80, anchor='nw')
en2.insert(0, '8888')

# sock_main = socket.socket()

def socket_command(thread_name, cmd):
    local_sock = socket.socket()
    print('** thread_name: {}'.format(thread_name))
    print('ip: {}, port: {}'.format(ip_var.get(), port_var.get()))
    local_sock.connect((ip_var.get(), int(port_var.get())))
    local_sock.send((cmd+'\n').encode('utf-8'))

    while True:
        recv_str = str(local_sock.recv(1024), encoding='utf-8')
        if recv_str == cmd+'_ok':
            print('**** recv: {}'.format(recv_str))
            local_sock.send('exit\n'.encode('utf-8'))
            local_sock.close()



# def socket_connect():
#     sock_main.connect((ip_var.get(), int(port_var.get())))
    # sock.connect(('10.201.0.26', 8888))

# def socket_disconnect():
#     sock_main.close()

def socket_exposure():
    _thread.start_new_thread( socket_command, ('thread_exposure','exposure') )
    # thread = threading.Thread( target=socket_command, args=('thread_exposure','exposure') )
    # thread.start()
    # thread.join()

def socket_abort():
    _thread.start_new_thread( socket_command, ('thread_abort','abort') )
    # thread = threading.Thread( target=socket_command, args=('thread_exposure','abort') )
    # thread.start()
    # thread.join()

# 登录按钮
# tk.Button(window, text='登录', command=login).place(x=280, y=350)
# tk.Button(window, text='Connect', command=socket_connect).place(x=280, y=200)
# tk.Button(window, text='Disconnect', command=socket_disconnect).place(x=280, y=250)

tk.Button(window, text='Exposure', command=socket_exposure).place(x=280, y=300)
tk.Button(window, text='AbortExp', command=socket_abort).place(x=280, y=350)


# window.attributes('-topmost', 'true')
# window.after_idle(window.attributes,'-topmost',False)
window.mainloop()